﻿@typeparam TItem where TItem : class,new()

@inject IJSRuntime JS


<CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaMenu Text="导出数据" Icon="mdi-database-export " TextStyle>
    <div style=" display: flex; flex-direction: column;">
        <CnGalWebSite.Components.Buttons.MasaButton TextStyle Text="Json" Icon="mdi-code-json " IsAsync OnClick="OnExportJson" />
    </div>
</CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaMenu>

@code {

    [Parameter]
    public IEnumerable<TItem> Items { get; set; }
    [Parameter]
    public string Name { get; set; }


    [Parameter]
    public Func<Task<IEnumerable<TItem>>> OnQueryAsync { get; set; }

    public async Task<IEnumerable<TItem>> GetData()
    {
        IEnumerable<TItem> items = null;
        if (OnQueryAsync != null)
        {
            items = await OnQueryAsync.Invoke();
        }
        else
        {
            items = Items;
        }

        return items;
    }

    public async Task OnExportJson()
    {

        //获取
        var items = await GetData();
        //检查
        if (items == null || items.Any() == false)
        {
            return;
        }


        //生成json

        var json= Newtonsoft.Json.JsonConvert.SerializeObject(items);

        var fileStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));

        await DownloadFileFromStream(fileStream, $"{Name} - {items.Count()}条记录.json");
    }

   

    private async Task DownloadFileFromStream(MemoryStream fileStream, string fileName)
    {

        using var streamRef = new DotNetStreamReference(stream: fileStream);

        await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
    }
}
